package com.zy.mc_module.base.kotlin

import android.content.Context
import android.content.Intent
import android.content.res.Resources
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.view.View
import android.view.inputmethod.InputMethodManager
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.RecyclerView
import androidx.viewbinding.ViewBinding
import com.chad.library.adapter.base.BaseQuickAdapter
import com.hwangjr.rxbus.RxBus
import com.kingja.loadsir.callback.Callback
import com.kingja.loadsir.core.LoadService
import com.kingja.loadsir.core.LoadSir
import com.kingja.loadsir.core.Transport
import com.scwang.smartrefresh.layout.SmartRefreshLayout
import com.zy.mc_module.R
import com.zy.mc_module.base.App
import com.zy.mc_module.base.BaseAdapter
import com.zy.mc_module.mvp.base.IPresenter
import com.zy.mc_module.mvp.base.IView
import com.zy.mc_module.MainActivity
import com.zy.mc_module.utils.AppTools
import com.zy.mc_module.utils.FixMemLeak
import com.zy.mc_module.utils.StringsUtils
import com.zy.mc_module.utils.loadsir.EmptyCallback
import com.zy.mc_module.utils.loadsir.ErrorCallback
import com.zy.mc_module.utils.loadsir.LoadingCallback
import io.reactivex.subjects.PublishSubject
import java.util.*

abstract class BaseActivity<V : IView, P : IPresenter<V>, VB : ViewBinding>() : AppCompatActivity() {

    lateinit var binding: VB
    var TAG: String = this::class.java.simpleName
    lateinit var context: Context
    protected var publishSubject: PublishSubject<Any>? = null
    public var presenter: P? = null
    private var loadService: LoadService<*>? = null

    //使用LoadSir
    private var isNeedLoadSir = false

    //指定需要加载的视图
    private var loadView: View? = null

    protected var mDistance = 0

    //下拉刷新
    private var refreshLayout: SmartRefreshLayout? = null
    private var recyclerView: RecyclerView? = null

    /**
     * 分页加载
     */
    protected var page = 1 //页数

    protected var size = 10 //每页数目

    /***
     * 布局Id
     */
    abstract fun getViewBinding(): VB

    override fun startActivity(intent: Intent?) {
        super.startActivity(intent)
        overridePendingTransition(R.anim.activity_in_from_right, R.anim.activity_out_from_left)
    }

    override fun startActivityForResult(intent: Intent?, requestCode: Int) {
        super.startActivityForResult(intent, requestCode)
        overridePendingTransition(R.anim.activity_in_from_right, R.anim.activity_out_from_left)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        // 8.0 Only fullscreen opaque activities can request orientation
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            setTheme(R.style.AppTheme8)
        }
        context = this@BaseActivity;
        //修改底部导航栏颜色
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            window.navigationBarColor = Color.parseColor("#fcfcfc")
        }
        super.onCreate(savedInstanceState)
        binding = getViewBinding()
        setContentView(binding.root)
        //添加Activity
        App.getInstance().addActivity(this)
        //初始化P层
        presenter = createPresenter()
        if (null != presenter) {
            //绑定Activity
            presenter?.attachView(this as V)
        }
        //是否使用RxBus
        if (isNeedRxBus()) {
            RxBus.get().register(this)
        }
        //注册loadsir
        initLoadsir()
        //初始化视图
        initView()
        initView(savedInstanceState)
        //初始化事件
        initListener()
    }

    /***
     * 注册LoadSir
     */
    private fun initLoadsir() {
        //判断LoadSir
        isLoadSir()
        //是否使用LoadSir
        if (isNeedLoadSir) {
            //判断 是否指定了需要加载的视图
            loadService = LoadSir.getDefault().register(if (null == loadView) this else loadView
            ) {
                //重新加载逻辑
                reloadData()
            }
        }
    }

    /***
     * 创建Mvp Presenter实例
     */
    open fun createPresenter(): P? {
        return null
    }

    open protected fun initView() {}

    open fun initView(savedInstanceState: Bundle?) {}

    open protected fun initListener() {}

    /***
     * LoadSir的重新加载数据
     */
    open fun reloadData() {}

    /***
     * 是否使用LoadSir等一系列功能
     * arg[0]:使用LoadSir
     * arg[1]:指定需要加载的视图
     */
    open fun isLoadSir(vararg objects: Any) {
        if (objects.size == 1) {
            //使用LoadSir,未指定加载视图
            isNeedLoadSir = objects[0] as Boolean
            loadView = null
        } else if (objects.size == 2) {
            //使用LoadSir,并指定需要加载视图
            isNeedLoadSir = objects[0] as Boolean
            loadView = findViewById((objects[1] as Int))
        }
    }

    /***
     * 是否使用RxBus,默认false
     */
    open fun isNeedRxBus(): Boolean {
        return false
    }

    /***
     * 封装下拉刷新/上拉加载逻辑
     */
    protected fun initRefresh(refreshLayout: SmartRefreshLayout, recyclerView: RecyclerView?) {
        this.recyclerView = recyclerView
        this.refreshLayout = refreshLayout

        //下拉刷新
        refreshLayout.setOnRefreshListener { refreshlayout ->
            refreshlayout.setEnableLoadMore(true)
            page = 1
            refreshData(true)
        }
        //上拉加载
        refreshLayout.setOnLoadMoreListener {
            page++
            refreshData(false)
        }
    }

    /***
     * 刷新加载数据
     */
    open fun refreshData(ReOrLo: Boolean) {}

    /***
     * 刷新完成
     */
    protected fun refreshComplete(any: Any?) {
        if (any is MutableList<*>) {
            val list: MutableList<*> = any
            val recyclerViewAdapter = recyclerView?.adapter
            if (null != recyclerViewAdapter) {
                if (recyclerViewAdapter is BaseAdapter<*>) {
                    val adapter = recyclerView?.adapter as BaseAdapter<Any>?
                    if (page == 1) {
                        adapter!!.setAll(list)
                        if (adapter.list.size > 0) {
                            recyclerView!!.scrollToPosition(0)
                        }
                    } else {
                        adapter!!.addAll(list)
                    }
                } else if (recyclerViewAdapter is BaseQuickAdapter<*, *>) {
                    val adapter = recyclerView!!.adapter as BaseQuickAdapter<Any, *>?
                    if (page == 1) {
                        adapter!!.setNewData(list)
                        if (adapter.data.size > 0) {
                            recyclerView!!.scrollToPosition(0)
                        }
                    } else {
                        adapter?.addData(Collections.addAll(list))
                    }
                }
            }
            if (StringsUtils.isEmpty(list) && page > 1) {
                page--
                refreshLayout!!.setEnableLoadMore(false)
            }
        } else if (any is Boolean) {
            if (any && page > 1) {
                page--
            }
        }
        AppTools.finishRefresh(refreshLayout)
    }

    //--------------------------------LoadSir的反馈页-----------------------------------

    //--------------------------------LoadSir的反馈页-----------------------------------
    /***
     * 显示加载页
     */
    fun showLoading() {
        loadService!!.showCallback(LoadingCallback::class.java)
    }

    /***
     * 关闭加载页
     */
    fun disLoading() {
        loadService!!.showSuccess()
    }

    fun disLoading(time: Long) {
        Handler().postDelayed({ loadService!!.showSuccess() }, time)
    }

    /***
     * 暂无数据页
     */
    fun showEmpty() {
        loadService!!.showCallback(EmptyCallback::class.java)
    }

    fun showEmpty(callback: Class<out Callback?>?) {
        loadService!!.showCallback(callback)
    }

    fun showEmpty(list: List<*>?) {
        if (null == list || list.size <= 0) {
            loadService!!.showCallback(EmptyCallback::class.java)
        } else {
            disLoading()
        }
    }

    fun showEmpty(list: MutableList<*>?, callback: Class<out Callback?>?) {
        if (null == list || list.size <= 0) {
            loadService!!.showCallback(callback)
        } else {
            disLoading()
        }
    }

    /***
     * 请求错误页
     */
    fun showError() {
        loadService!!.showCallback(ErrorCallback::class.java)
    }

    fun showError(list: MutableList<*>?) {
        if (null == list || list.size <= 0) {
            loadService!!.showCallback(ErrorCallback::class.java)
        } else {
            disLoading()
        }
    }
    //----------------------------------------

    //----------------------------------------
    override fun getResources(): Resources? {
//        //字体不随系统字体变化
//        Resources resources = super.getResources();
//        Configuration newConfig = resources.getConfiguration();
//        DisplayMetrics displayMetrics = resources.getDisplayMetrics();
//
//        if (resources != null && newConfig.fontScale != 1) {
//            newConfig.fontScale = 1;
//            if (Build.VERSION.SDK_INT >= 17) {
//                Context configurationContext = createConfigurationContext(newConfig);
//                resources = configurationContext.getResources();
//                displayMetrics.scaledDensity = displayMetrics.density * newConfig.fontScale;
//            } else {
//                resources.updateConfiguration(newConfig, displayMetrics);
//            }
//        }
        //屏幕适配
        //AutoSizeCompat.autoConvertDensityOfGlobal(super.getResources())
        return super.getResources()
    }

    /**
     * 隐藏键盘
     */
    protected fun hideInput() {
        //et_con.setFocusable(false);
        val imm = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
        val v = window.peekDecorView()
        if (null != v) {
            imm.hideSoftInputFromWindow(v.windowToken, 0)
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        if (isNeedRxBus()) {
            //注销RxBus
            RxBus.get().unregister(this)
        }
        if (null != presenter) {
            presenter!!.detachView()
            presenter = null
        }
        //取消订阅
        //SubscriptionManager.getInstance().cancelall();
        App.getInstance().removeActivity(this)
        App.getInstance().removeTmpActivity(this)
        //----
        //ShareUtil.recycle();
        FixMemLeak.fixLeak(context)
    }

    override fun finish() {
        super.finish()
        overridePendingTransition(R.anim.activity_in_from_left, R.anim.activity_out_from_right)
    }

    /**
     * -----------------------解决微信分享成功后,留在微信不回调分享成功的问题start-------------------------------------------
     */
    var isSharing   = false//是否调起了分享。如果调起分享，这个值为true。

    private var isResume = false//Activity是否处于前台。

    override fun onResume() {
        super.onResume()
        isSharing = false
        isResume = true
    }

    override fun onPause() {
        super.onPause()
        isResume = false
    }
}